package com.dys.hejiayuncommunity.system.service.impl;

import com.dys.hejiayuncommunity.system.domain.SysArea;
import com.dys.hejiayuncommunity.system.domain.dto.AreaDTO;
import com.dys.hejiayuncommunity.system.mapper.SysAreaMapper;
import com.dys.hejiayuncommunity.system.service.SysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: com.dys.hejiayuncommunity.system.service.impl.SysAreaServiceImpl
 * @description: 区域相关服务类
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/12/05 21:34
 */
@Service
public class SysAreaServiceImpl implements SysAreaService {
    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Override
    public List<AreaDTO> findAreaAsTree() {
        // 1.获取区域表数据
        List<SysArea> listArea = sysAreaMapper.selectAllArea();
        return listArea.stream()
                .filter(area -> area.getParentCode().equals(0))// 筛选区域为0的根节点对象
                .map(area -> {
                    // 将Area进行转换
                    AreaDTO areaDTO = new AreaDTO();
                    areaDTO.setCode(area.getCode());
                    areaDTO.setName(area.getName());
                    areaDTO.setChildren(getChildrenArea(areaDTO, listArea));
                    return areaDTO;
                }).collect(Collectors.toList());
    }

    /**
     * 递归设置区域信息
     *
     * @param areaDTO 上级区域信息
     * @param list    所有区域信息
     * @return 子级区域列表
     */
    private List<AreaDTO> getChildrenArea(AreaDTO areaDTO, List<SysArea> list) {
        List<SysArea> subAreaList = list.stream().filter(area -> area.getParentCode().equals(areaDTO.getCode())) // 获取当前父区域的子节点
                .collect(Collectors.toList());// 把当前流转换为一个List集合

        if (subAreaList != null && !subAreaList.isEmpty()) {
            return subAreaList.stream().map(area -> {
                AreaDTO subAreaDto = new AreaDTO();
                subAreaDto.setName(area.getName());
                subAreaDto.setCode(area.getCode());
                // 设置子节点,递归调用直到获取到叶子结点为止
                subAreaDto.setChildren(getChildrenArea(subAreaDto, list));
                return subAreaDto;
            }).collect(Collectors.toList());
        }
        return null;
    }
}
